package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.qf.entity.WeiXinResult;
import com.qf.service.OrderService;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package ${PACKAGE_NAME}
 * @description: ${TODO}
 * @date 2022/6/27 10:27
 */
@WebServlet(name = "PaySuccessServlet",urlPatterns = "/paySuccess")
public class PaySuccessServlet extends HttpServlet {

    private OrderService orderService;

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("支付成功");
        // result
        String json = request.getParameter("result");
        //1校验
        if(StringUtils.isEmpty(json)){
            request.setAttribute("msg","支付失败" );
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
        }
        //2把JSON字符串转成Java对象
        try {
            WeiXinResult result=JSON.parseObject(json, WeiXinResult.class);
            String oid = result.getResult().getOutTradeNo();
            if(result.getResult().getResultCode().equals("SUCCESS")){
                //支付成功
                //修改订单状态

                orderService.updateStatus(oid,"2");
                request.setAttribute("msg",oid+" 支付成功,等待发货~~~~" );
            }else{
                //支付失败
                request.setAttribute("msg",oid+" 支付失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","支付失败:"+e.getMessage());
        }
        request.getRequestDispatcher("/message.jsp").forward(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
